<template>
  <div class="universal-form">
    <div class="membersbox pad50">
      <form
        action=""
        method="POST"
        class="diy-phone-form no-border phone_border"
      >
        <div class="diy-phone-header">
          <div class="diy-phone-box">
            <div class="diy-phone-list">
              <p class="title" :class="fontSizeTitle">{{ formTitle }}</p>
              <div class="remark" v-if="remark" v-html="remark"></div>
              <template v-if="infoData.has_submit != 1">
                <ul>
                  <div v-for="(item, index) in formList" :key="index">
                    <div v-if="item.type == 1">
                      <li>
                        <div>
                          <p class="clearfix">
                            <span
                              v-if="item.is_required == 1"
                              class="colorRed must fl"
                              >*</span
                            >
                            <b class="fl">{{ item.name }}</b>
                          </p>
                          <div class="clearfix select_box">
                            <div
                              class="s"
                              v-if="item.lists1 && item.lists1.length > 0"
                            >
                              <!-- TODO 小程序使用wx-picker -->
                              <wx-picker
                                @change="handleClickOption1"
                                :value="item.choose"
                                :data-itemdata="item"
                                :range="item.lists1"
                              >
                                <span>{{ item.choose }}</span>
                              </wx-picker>
                            </div>

                            <div
                              class="s"
                              v-if="
                                item.secondList && item.secondList.length > 0
                              "
                            >
                              <!-- TODO 小程序使用wx-picker -->
                              <wx-picker
                                @change="handleClickOption2"
                                :value="item.choose2"
                                :data-itemdata="item"
                                :range="item.secondList"
                              >
                                <span>{{ item.choose2 }}</span>
                              </wx-picker>
                            </div>
                          </div>
                        </div>
                      </li>
                    </div>
                    <div v-else-if="item.type == 2">
                      <li>
                        <div>
                          <p class="clearfix">
                            <span v-if="item.is_required == 1" class="colorRed must fl">*</span>
                            <b class="fl">{{ item.name }}</b>
                          </p>
                          <div class="clearfix select_box">
                              <div v-if="item.valueNew && item.valueNew.length > 0">
                                <van-checkbox-group class="purchase_agreement" direction="horizontal" v-model="item.choose">
                                    <van-checkbox v-for="(value,ind) in item.valueNew" :key="ind"
                                                  :name="value.title" checked-color="#F30C23" shape="square" icon-size="16px"><span
                                      class="tips">{{ value.title }}</span>
                                    </van-checkbox>
                                </van-checkbox-group>
                              </div>

                          </div>
                        </div>
                      </li>
                    </div>
                    <div v-else>
                      <li>
                        <div>
                          <p class="clearfix">
                            <span
                              :class="item.is_required > 0 ? 'must' : ''"
                              class="colorRed fl"
                              >*</span
                            >
                            <b class="fl">{{ item.name }}</b>
                          </p>
                          <input
                            type="text"
                            v-model="item.value"
                            name="info_list[]"
                            class="input"
                          />
                        </div>
                      </li>
                    </div>
                  </div>
                  <!-- 上传图片 -->
                  <div v-if="isUploadImg === 1">
                    <li>
                      <div>
                        <p class="clearfix">
                          <span class="colorRed fl must">*</span>
                          <b class="fl">上传照片（最多18张）</b>
                        </p>
                        <SmallUploadImg
                          ref="smallUploadImg"
                          :maxLength="18"
                          @changeImgList="changeImgList"
                          :isChangeStyle="true"
                        ></SmallUploadImg>
                      </div>
                    </li>
                  </div>
                  <!-- 上传视频 -->
                  <div v-if="isUploadVideo === 1">
                    <li>
                      <div>
                        <p class="clearfix">
                          <span class="colorRed fl must">*</span>
                          <b class="fl">上传视频</b>
                        </p>
                        <SmallUploadImg
                          ref="smallUploadVideo"
                          :maxLength="1"

                          type="video"
                          @changeImgList="uploadVideoListIssue"
                          @showVideo="showVideo"
                        ></SmallUploadImg>
                      </div>
                    </li>
                  </div>
                </ul>
              </template>
              <!-- + -->
              <template v-else>
                <ul>
                  <div v-for="(val, key, index) in result.info" :key="index">
                    <div>
                      <li>
                        <div>
                          <p class="clearfix">
                            <b class="fl">{{ key }}</b>
                          </p>
                          <input
                            type="text"
                            :value="val"
                            name="info_list[]"
                            class="input"
                            :disabled="true"
                          />
                        </div>
                      </li>
                    </div>
                  </div>
                  <!-- 上传图片 -->
                  <div v-if="isUploadImg === 1">
                    <li>
                      <div>
                        <p class="clearfix">
                          <b class="fl">上传照片（最多5张）</b>
                        </p>
                        <div class="img-wrap">
                          <div
                            class="imageItem-box"
                            v-for="(item, index) in result.picsmap"
                            :key="index"
                          >
                            <img
                              class="imageItem"
                              :src="item"
                              lazy-load="true"
                              @click="previewImage(item)"
                            />
                          </div>
                        </div>
                      </div>
                    </li>
                  </div>
                  <!-- 上传视频 -->
                  <div v-if="isUploadVideo === 1">
                    <li>
                      <div>
                        <p class="clearfix">
                          <b class="fl">视频</b>
                        </p>

                        <img v-for="(img,index) in result.postUrl" @click="videoPreview(index)" :key="index" :src="img"
                          class="post-video">
                      </div>
                    </li>
                  </div>
                </ul>
              </template>

              <template v-if="infoData.has_submit != 1">
                <a
                  v-if="itemId && itemId > 0"
                  href="javascript:;"
                  class="ljbm"
                  @click="handleClickPayment"
                  >立即支付</a
                >
                <a
                  v-else
                  href="javascript:;"
                  class="ljbm"
                  @click="handleClickSubmit"
                  >立即提交</a
                >
              </template>
              <wx-button open-type="share" class="ljbm">立即分享</wx-button>
            </div>
          </div>
        </div>
      </form>
      <div class="bgPop" v-if="videoShow" @click.stop="videoHide()">
        <img src="https://img.wifenxiao.com/h5-wfx/images/activity/icon_close.png" @click.stop="videoHide()" class="close">
        <video :src="videoMp" autoplay controls></video>
      </div>
      <b id="htmlReplace-navCart"></b>
      <!-- 授权弹出框 -->
      <small-login ref="smalllogin"></small-login>
    </div>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import Vue from "vue";
import Store from "@/utils/store";
import { getFormInfo, formSubmit } from "@/api/item/activity";
import { mpShare } from "@/utils/utils";
import small from "@/smallapp/small";
import SmallLogin from "@/components/SmallLogin/smallLogin.vue";
import SmallUploadImg from "@/components/SmallUploadImg/index.vue";
import { CheckboxGroup } from 'vant'
Vue.use(CheckboxGroup)
export default Vue.extend({
  name: "index",
  data() {
    return {
      infoData: {},
      result: {
        info: [],
        picsmap: [],
        videoUrl: [],
        postUrl: []
      },
      videoShow: false,
      videoMp: '',
      fileListVideo: [],
      videoList: [],
      isUploadVideo: 0,

      formId: "",
      formList: [],
      fileList: [],
      formTitle: "",
      remark: "",
      isUploadImg: 0,
      fontSizeTitle: "",
      itemId: "",
      formData: {
        biao_dan_id: "",
      },
      disabled: false,
    };
  },
  components: {
    SmallLogin,
    SmallUploadImg,
  },
  methods: {
    uploadVideoListIssue(val) {
      const arr = []
      const post = []
      val.forEach(item => {
        console.log("item", item)
        arr.push(item.file_path)
        post.push(item.pic)
      })
      this.formData.movie_list = arr
      this.formData.movie_cover_list = post
    },
    videoPreview(index) {
      this.videoShow = true
      this.videoMp = this.result.videoUrl[index]
    },
    showVideo(item) {
      this.videoShow = true
      this.videoMp = item.file_path
    },
    videoHide() {
      this.videoShow = false
      this.videoMp = ''
    },
    previewImage(current) {
      wx.previewImage({
        current,
        urls: this.result.picmap
      })
    },
    changeImgList(imgList) {
      // console.log("imgList", imgList);
      this.formData.image_list = imgList.join(",");
    },
    // 获取默认数据
    getFormInfoFn() {
      this.$loadingWrap.show();
      setTimeout(() => {
        this.$loadingWrap.close();
      }, 50000);
      getFormInfo({ id: this.formId }).then((res) => {
        this.$loadingWrap.close();
        if (res.status == 1) {
          const formList = res.data.list;
          formList.forEach((item) => {
            if (item.type == 1) {
              if (item.lists2[0]) item.secondList = item.lists2[0] || [];
              item.choose = item.lists1[0];
              item.choose2 = item.secondList[0];
            } else if (item.type == 2) {
              var list = JSON.parse(item.val)
              item.valueNew = list.filter(item => item.title && item.title.trim().length > 0)
              item.choose = []
            }
          });
          this.formList = formList;
          this.result = res.data.result || {}
          // console.log('reilttt', this.result)
          this.result.picsmap = []
          this.result.videoUrl = this.result.movie_url
          this.result.postUrl = this.result.movie_cover_url
          if (this.result.img_url && this.result.img_url.length > 0) {
            this.result.picsmap = this.result.img_url
          }
          this.isUploadImg = res.data.is_upload_img || 0;
          this.isUploadVideo = res.data.is_upload_movie || 0
          this.formTitle = res.data.title;
          this.remark = res.data.remark;
          if (this.formTitle) {
            wx.setNavigationBarTitle({
              title: res.data.title,
            });
          }
          this.itemId = res.data.item_id;
          if (this.formTitle.length > 8 && this.formTitle.length < 16) {
            this.fontSizeTitle = "fontSize16";
          } else if (this.formTitle.length >= 16) {
            this.fontSizeTitle = "fontSize12";
          }
          this.infoData = res.data;
          // TODO 小程序分享
          const option = {
            title: this.formTitle,
            imgUrl: res.data.share_img,
            shareParam: `id=${res.data.biao_dan_id}&sid=${
              small.globalData.shopId
            }&pid=${
              small.wxCache("global_login_info")
                ? small.wxCache("global_login_info").uid
                : "0"
            }`,
          };
          mpShare(true, true, "/activity/pages/universalForm/index", option);
        } else {
          this.$Error(res.msg);
        }
      });
    },
    // 选择了select
    handleClickOption(index, data) {
      const formList = this.formList;
      formList.forEach((item) => {
        if (item.type == 1) {
          item.lists1.forEach((opt, num2) => {
            if (data.choose == opt) {
              item.secondList = item.lists2[num2];
              item.choose2 = item.secondList[0];
            }
          });
        }
      });
      this.formList = formList;
    },
    handleClickOption1(event) {
      const itemdata = event.target.dataset.itemdata;
      const formList = this.formList;
      formList.forEach((item) => {
        if (item.type == 1) {
          item.lists1.forEach((opt, num2) => {
            // console.log(opt, num2);
            if (
              item.lists1[event.detail.value] == opt &&
              itemdata.biao_dan_config_id == item.biao_dan_config_id
            ) {
              item.secondList = item.lists2[num2];
              item.choose = item.lists1[event.detail.value];
              item.choose2 = item.secondList[0];
            }
          });
        }
      });
      // console.log(formList, "formList");
      this.formList = formList;
    },
    handleClickOption2(event) {
      const formList = this.formList;
      const itemdata = event.target.dataset.itemdata;
      formList.forEach((item) => {
        if (item.type == 1) {
          item.secondList.forEach((opt, num2) => {
            if (
              item.secondList[event.detail.value] == opt &&
              itemdata.biao_dan_config_id == item.biao_dan_config_id
            ) {
              item.choose2 = item.secondList[event.detail.value];
            }
          });
        }
      });
      this.formList = formList;
    },
    // 立即支付
    handleClickPayment() {
      this.validateData();
      if (!this.locked) {
        const formData = this.dealFormData();
        Store.save("formBuy", formData);
        this.$JumpName(this, "formBuy", {});
      }
    },
    // 立即提交
    handleClickSubmit() {
      this.validateData();
      if (!this.locked) {
        const formData = this.dealFormData();
        this.$loadingWrap.show();
        setTimeout(() => {
          this.$loadingWrap.close();
        }, 50000);
        formSubmit(formData).then((res) => {
          this.$loadingWrap.close();
          if (res.status == 1) {
            this.$JumpName(this, "index");
            this.$Error("提交成功");
          } else {
            this.$Error(res.msg);
          }
        });
      }
    },
    // 验证数据
    validateData() {
      this.locked = false;
      const formList = JSON.stringify(this.formList);
      const formListreverse = JSON.parse(formList).reverse();
      // // console.log(formList, 11111)
      formListreverse.forEach((item) => {
        if (item.is_required == 1) {
          if (!item.value && item.type == 0) {
            this.$Error(`请输入${item.name}`);
            this.locked = true;
          } else if (!item.choose && item.type == 1) {
            this.$Error(`请选择${item.name}`);
            this.locked = true;
            return false;
          } else if (item.type == 2 && (!item.choose || item.choose.length == 0)) {
            this.$Error(`请选择${item.name}`)
            this.locked = true
            return false
          }
        }
      });
      if (this.isUploadImg === 1) {
        if (!this.formData.image_list) {
          this.$Error("请上传图片");
          this.locked = true;
          return false;
        }
      }
      if (this.isUploadVideo === 1) {
        if (!this.formData.movie_list) {
          this.$Error('请上传视频')
          this.locked = true
          return
        }
      }
    },
    // 处理数据
    dealFormData() {
      const formList = this.formList;
      const formData = Object.assign({}, this.formData, true);
      formData.biao_dan_id = this.formId;
      formData.info_list = [];
      formData.info_list_select1 = [];
      formData.info_list_select2 = [];
      formData.multiple_data = []
      formList.forEach((item) => {
        if (item.type == 1) {
          formData.info_list_select1.push(item.choose);
          formData.info_list_select2.push(item.choose2);
        } else if (item.type == 2) {
          formData.multiple_data.push({
            title: item.name,
            data: item.choose
          })
        } else {
          formData.info_list.push(item.value || "");
        }
      });
      if (this.isUploadVideo === 1) {
        formData.movie_list = formData.movie_list.join(",")
        formData.movie_cover_list = formData.movie_cover_list.join(";")
      }
      return formData;
    },
  },
  mounted() {
    window.addEventListener("wxload", (query) => {
      // console.log(query, this.$route.query, "分享参数");
      this.formId = query.id || this.$route.query.id;
      this.getFormInfoFn();
      small.HandleShareParams();
    });

    window.addEventListener("wxshow", () => {
      if (!small.checkLogin()) {
        this.$refs.smalllogin.openSmallLoginPop();
      }
    });

    window.$$subscribe("loginReload", (reload) => {
      if (reload) {
        this.getFormInfoFn();
      }
    });
  },
});
</script>

<style lang="scss">
.miniprogram-root {
  .select_box {
    display: flex;
    justify-content: space-between;
    .s {
      width: 48%;
    }
    .van-checkbox--horizontal {
      margin-bottom: 20px;
    }

  }
}
.universal-form {
  ::-webkit-scrollbar {
    display: none;
  }

  .diy-phone-form.phone_border {
    width: 100%;
    height: auto;
  }

  .diy-phone-form .diy-phone-header {
    width: 100%;
    height: 100%;
    overflow: auto;
    position: relative;
    left: 50%;
    transform: translateX(-50%);
    z-index: 1;
    background: #e9403d;
    background-size: 100% auto;
    padding-bottom: 32px;
  }
  .diy-phone-form .diy-phone-header .diy-phone-box {
    height: 100%;
    width: 100%;
    padding-top: 12vw;
  }

  .diy-phone-form .diy-phone-header .diy-phone-box .diy-phone-list {
    width: auto;
    margin: 0 32px;
    background-color: #fff;
    border-radius: 12px;
    padding-bottom: 100px;
    height: auto;
  }

  .diy-phone-form .diy-phone-header .diy-phone-box .diy-phone-list .title {
    width: 580px;
    height: 92px;
    background: url("https://img.wifenxiao.com/h5-wfx/images/activity/un_bd_title.png")
      no-repeat;
    background-size: 100%;
    margin: 0 auto;
    position: relative;
    top: -18px;
    text-align: center;
    line-height: 92px;
    color: #fff;
    font-size: 36px;
    &.fontSize16 {
      font-size: 32px;
    }
    &.fontSize12 {
      font-size: 24px;
    }
  }
  .remark {
    margin: 24px 46px;
    text-align: center;
  }

  .diy-phone-form .diy-phone-header .diy-phone-box .diy-phone-list ul {
    width: auto;
    height: auto;
    margin: 0 66px;
    background-color: #fff;
  }

  .diy-phone-form .diy-phone-header .diy-phone-box .diy-phone-list ul li {
    width: 100%;
    margin-bottom: 8px;
  }

  .diy-phone-form .diy-phone-header .diy-phone-box .diy-phone-list ul li p {
    line-height: 64px;
  }
  .diy-phone-form .diy-phone-header .diy-phone-box .diy-phone-list ul li b {
    font-size: 26px;
  }

  .diy-phone-form
    .diy-phone-header
    .diy-phone-box
    .diy-phone-list
    ul
    li
    p
    span {
    display: none;
    margin-right: 6px;
  }

  .diy-phone-form
    .diy-phone-header
    .diy-phone-box
    .diy-phone-list
    ul
    li
    p
    span.must {
    display: inline;
  }

  .diy-phone-form .diy-phone-header .diy-phone-box .diy-phone-list ul li input {
    width: 96%;
    padding: 0 2%;
    height: 60px;
    border: 2px solid #e5e5e5;
    border-radius: 8px;
    color: #333;
  }
  .diy-phone-form .diy-phone-header .diy-phone-box .diy-phone-list ul li select,
  .diy-phone-form
    .diy-phone-header
    .diy-phone-box
    .diy-phone-list
    ul
    li
    picker {
    width: 48%;
    padding: 0 2%;
    height: 64px;
    line-height: 64px;
    font-size: 26px;
    border: 2px solid #e5e5e5;
    background-color: #fff;
    border-radius: 8px;
    color: #333;
  }
  .diy-phone-form
    .diy-phone-header
    .diy-phone-box
    .diy-phone-list
    ul
    li
    picker {
    width: 90%;
  }

  .ljbm {
    width: 456px;
    display: block;
    margin: 32px auto 0;
    line-height: 76px;
    text-align: center;
    color: #fff;
    font-size: 30px;
    border-radius: 8px;
    background: linear-gradient(to right, #ff794a, #f32722);
  }

  .pad50 {
    padding-bottom: 100px;
  }  
}
.img-wrap {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  padding-top:20px;
  align-content: center;
  .imageItem-box{
    width: 157px;
    height: 157px;
    margin-right: 20px;
    margin-bottom: 20px;
    position: relative;
    .imageItem{
      width: 100%;
      height: 100%;
    }
  }
}
.post-video {
  width: 160px;
  height: 160px;
  margin-right: 10px;
  object-fit: cover;
}

.bgPop {
  background: rgba(0, 0, 0, 0.5);
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 999;
  display: flex;
  align-items: center;
  justify-content: center;

  .close {
    position: absolute;
    top: 20px;
    right: 20px;
    width: 50px;
    height: 50px;
  }

  video {
    width: 90%;
  }
}
</style>
